package dst1.query;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

import dst1.model.Execution;
import dst1.model.Job;
import dst1.model.JobStatus;

public class HibernateCriteria {

	private Session session;
	
	public HibernateCriteria(EntityManager em){
		session = (Session)em.getDelegate();
	}
	
	public List<Job> findAllJobsByUserAndWorkflow(String username, String workflowname){
		
		session.getTransaction().begin();
		
		Criteria crit = session.createCriteria(Job.class);
		
		if(username != null){
			
			crit.createCriteria("user").add(Restrictions.eq("username", username));
		}
		
		if(workflowname != null){
			crit.createCriteria("environment").add(Restrictions.eq("workflow", workflowname));
		}
		
		List<Job> jobs = crit.list();
		
		session.getTransaction().commit();
		return jobs;
		
	}
	
	public List<Job> findJobsByExample(Date start, Date end){
		Execution ex = new Execution(null, null,JobStatus.FINISHED, null, null);
		if(start != null){
			ex.setStart(start);
		}
		if(end != null){
			ex.setEnd(end);
		}
		
		session.getTransaction().begin();
		Criteria crit = session.createCriteria(Job.class).createCriteria("execution");
		crit.add(Example.create(ex));
		
		List<Job> jobs = crit.list();
		
		session.getTransaction().commit();
		return jobs;
	}
}
